//
//  TuiHuanDetailViewController.m
//  Experss
//
//  Created by wmwMAC on 17/8/8.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "TuiHuanDetailViewController.h"

//#import "TuiHanTypeTableViewCell.h"//退换方式
#import "TuiHuoCauseTableViewCell.h"//退货原因
#import "TuiHuoPictureTableViewCell.h"//图片
//#import "TuiHuoYunFeiTableViewCell.h"//运费
#import "TuiHuoMoneyTableViewCell.h"

#import "TuiHuanCauseView.h"

#import "MyTextView.h"

#import "PayForViewController.h"// 支付页面


static NSString *MoneyIdentifier = @"TuiHuoMoneyTableViewCell";
static NSString *CauseIdentifier = @"TuiHuoCauseTableViewCell";
static NSString *PictureIdentifier = @"TuiHuoPictureTableViewCell";
//static NSString *YunfeiIdentifier = @"TuiHuoYunFeiTableViewCell";


@interface TuiHuanDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,TuiHuanCauseDelegate>
{
    NSArray *headerTitleArr;
    UIButton *applybtn;
    NSString *applyCause;//退款原因
    
//    NSString *temPostmoeny;//运费情况
//    NSString *tempWayOut;//退货方式
    NSString *textVTextStr;//申请原因
    NSArray *imageArrayN;//选择图片凭证的数组
    NSString *imagesStr;
    NSString *moenyTui;//协商的退款金额
    NSInteger i;
    
}
@property (nonatomic, strong) UITableView *tableView;
@end

@implementation TuiHuanDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"申请退货";
    
    
    applyCause = @"请选择申请原因";
    headerTitleArr = @[@"申请原因",@"退款金额",@"上传图片凭证",@"退款说明"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(putImageArrayAction:) name:@"putImageArrayAction" object:nil]; //注册通知用来接受上传图的凭证
    [self addTableviewUI];
    
}

#pragma mark －＝－＝－＝－＝注册通知用来获取存放图片凭证的数组
- (void)putImageArrayAction:(NSNotification *)notification{
    
    imageArrayN = [NSArray arrayWithArray:notification.userInfo[@"imageAray"]];

}
- (void)addTableviewUI {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-NAV_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = BaseColor;
//    [self.tableView registerNib:[UINib nibWithNibName:@"TuiHanTypeTableViewCell" bundle:nil] forCellReuseIdentifier:typeIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"TuiHuoCauseTableViewCell" bundle:nil] forCellReuseIdentifier:CauseIdentifier];
    [self.tableView registerClass:[TuiHuoPictureTableViewCell class] forCellReuseIdentifier:PictureIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"TuiHuoMoneyTableViewCell" bundle:nil] forCellReuseIdentifier:MoneyIdentifier];
    [self.view addSubview:self.tableView];
    
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
    self.tableView.tableFooterView = footView;
    
    applybtn = [BasePublicCreatUI createBtnFrame:CGRectMake(20, 20, kScreenWidth-40, 50) title:@"提交" bgImage:@"bg1" selectBgImage:nil image:nil target:self action:@selector(confirmApply:)];
    applybtn.layer.cornerRadius = 5;
    applybtn.clipsToBounds = YES;
    [applybtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [footView addSubview:applybtn];
    
    
}
#pragma mark  ------------ 确认申请 -------
-(void)confirmApply:(UIButton *)sender{
    if (imageArrayN.count) {
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        NSMutableArray *imageArray = [NSMutableArray array];
         i = 0;
        for (UIImage *imgStr in imageArrayN) {
            //压缩图片
            NSData *fileData = UIImageJPEGRepresentation(imgStr, 0.0);
            NSDictionary *dic = @{@"file":fileData};
            AFHTTPSessionManager *Manager = [AFHTTPSessionManager manager];
            Manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain",@"text/html", nil];
            
            [Manager POST:POST(FileURL) parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                [formData appendPartWithFileData:fileData name:@"file" fileName:@"file.png" mimeType:@"image/png"];
            } progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if ([responseObject[@"ret"] intValue] != 200)  {
                    return ;
                }
                [imageArray addObject:[[[responseObject objectForKey:@"data"] objectForKey:@"info"] objectForKey:@"url"]];
                i++;
                if (i == imageArrayN.count) {
                    
                    imagesStr = [[NSArray arrayWithArray:imageArray] componentsJoinedByString:@","];
                    [self confirmAction];
                }
                
                
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [self.view showTextNoActivity:@"服务器异常" timeLength:1];
            }];
            
            
            
        }
        
        
        
    }
    
    
    
    
    
    
    
   
}

-(void)confirmAction{
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    
    if ([applyCause containsString:@"请选择申请原因"]) {
        [MBProgressHUD showText:@"请选择申请原因"];
        return;
    }
    if ([self isBlankString:moenyTui] == YES) {
        [MBProgressHUD showText:@"请输入退款金额"];
        return;
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:saveDic[@"userid"] forKey:@"userid"];//用户ID]
    [dic setObject:_orderID forKey:@"order_id"];//订单 ID
    
    [dic setObject:applyCause forKey:@"note_title"];//退款原因标题
    [dic setObject:[Md5Apiway getMD5data:saveDic[@"userid"]] forKey:@"actoken"];
    [dic setObject:moenyTui forKey:@"price"];
   

    if (textVTextStr.length) {
        [dic setObject:textVTextStr forKey:@"note"];//退款原因,字数1-255
    }
    if (imagesStr.length) {
        [dic setObject:imagesStr forKey:@"voucher"];//退款凭证图片路径，多个逗号分割

    }
    
    //[dic setObject:tempWayOut forKey:@"mode"];//退款方式 1退款退货 2换货补发
    //[dic setObject:temPostmoeny forKey:@"freight"];//运费承担方 1买家承担 2卖家承担
    
    
    
    [HttpRequest postWithURLString:POST(Shop_OrderListOrderRefund) parameters:dic success:^(id responseObject) {
        NSLog(@"0-0-0-0--%@",responseObject);
        
        if ([responseObject[@"ret"] intValue] != 200) {
            [MBProgressHUD showText:@"申请退款退货失败，请联系客服"];
            return ;
        }
       NSString *codeStr =  responseObject[@"data"][@"code"];
        if (![[NSString stringWithFormat:@"%@",codeStr] isEqualToString:@"0"]) {
            [MBProgressHUD showText:responseObject[@"data"][@"msg"]];
            return;
        }
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.navigationController popViewControllerAnimated:YES];
        
                
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    }];
    
    

    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 50;
    }else if (indexPath.section == 1){
        return 60;
    }else if (indexPath.section == 2){
        return (kScreenWidth-5*20)/4 + 60;
    }else{
        return 60;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return headerTitleArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        TuiHuoCauseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CauseIdentifier forIndexPath:indexPath];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.NameLable.text = applyCause;
        
        
        return cell;
    }else if (indexPath.section == 1){
        TuiHuoMoneyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MoneyIdentifier forIndexPath:indexPath];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.leftTextF.placeholder = @"请输入与卖家协议后的退款金额";
        cell.leftTextF.keyboardType = UIKeyboardTypeNumberPad;
        
        [cell.phoneBtn addTarget:self action:@selector(phoneBtnCliked) forControlEvents:UIControlEventTouchUpInside];
        [cell.leftTextF addTarget:self action:@selector(tuiKuanJinE:) forControlEvents:UIControlEventEditingChanged];
    
        return cell;
        
    }else if (indexPath.section == 2){
        TuiHuoPictureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PictureIdentifier forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        
        return cell;
    }else{
        
        TuiHuoMoneyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MoneyIdentifier forIndexPath:indexPath];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.leftTextF.placeholder = @"请输入退款说明";
        cell.leftTextF.keyboardType = UIKeyboardTypeDefault;
        [cell.leftTextF addTarget:self action:@selector(tuiKuanJinE:) forControlEvents:UIControlEventEditingChanged];[cell.leftTextF addTarget:self action:@selector(tuiKuanShuoMing:) forControlEvents:UIControlEventEditingChanged];
        cell.lineVIew.hidden = YES;
        cell.phoneBtn.hidden = YES;
        cell.phoneImgView.hidden = YES;
        return cell;
        
    }
    
}

#pragma mark --------------- 打电话那按钮事件
-(void)phoneBtnCliked{
    NSMutableString *str22=[[NSMutableString alloc] initWithFormat:@"tel:%@",_telPhoneNum];
    UIWebView *callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str22]]];
    [self.view addSubview:callWebview];
 
}
-(void)tuiKuanJinE:(UITextField *)textF{
    
    NSLog(@"texf %@",textF.text);
    moenyTui = textF.text;
}
-(void)tuiKuanShuoMing:(UITextField *)textF{
    
    NSLog(@"texf %@",textF.text);
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 30;
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = BaseColor;
    
    UILabel *titleLable = [BasePublicCreatUI createLabelFrame:CGRectMake(20, 0, kScreenWidth-40, 30) title:headerTitleArr[section] textColor:[UIColor lightGrayColor] textAlignment:NSTextAlignmentLeft font:[UIFont systemFontOfSize:12]];
    
    [headerView addSubview:titleLable];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 0) {
        return 100;
    }else{
        return 0.001;

    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footview = [[UIView alloc] init];
    footview.backgroundColor = [UIColor whiteColor];
    if (section == 0) {
        MyTextView *textV = [[MyTextView alloc] initWithFrame:CGRectMake(20, 10, kScreenWidth-40, 80)];
        textV.placeholder = @"请详细描述您遇到的具体问题,有助于客服人员更快的处理";
        textV.delegate = self;
        
        
        [textV setAutocorrectionType:UITextAutocorrectionTypeNo];//关闭自动校正 联想
        [textV setAutocapitalizationType:UITextAutocapitalizationTypeNone];//关闭首字母大
        textV.delegate =self;
        [footview addSubview:textV];

    }
    return footview;
}
-(void)textViewDidChange:(UITextView *)textView{

   textVTextStr = textView.text;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        //申请原因
        TuiHuanCauseView *causeV = [[TuiHuanCauseView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        causeV.causeArr = @[@"质量有问题",@"我不想要了",@"颜色不符合",@"与图片不同",@"数量不准确"];
        causeV.delegate = self;
        [self.view.window addSubview:causeV];
        
    }

}


-(void)tuiHuanCause:(NSString *)cause CauseId:(NSString *)causeId{
    
    applyCause = cause;
    [self.tableView reloadData];
}
//判断一个字符串是否为空
- (BOOL) isBlankString:(NSString *)string {
    
    if (string == nil || string == NULL) {
        
        return YES;
        
    }
    
    if ([string isKindOfClass:[NSNull class]]) {
        
        return YES;
        
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        
        return YES;
        
    }
    
    return NO;
    
}


@end
